// menu.js
const request = require('../../utils/request.js');
const util = require('../../utils/util.js');

Page({
  data: {
    categories: [],
    dishes: [],
    dishGroups: [],
    activeCategory: 0,
    keyword: '',
    loading: false,
    cartMap: {}, // 购物车映射：{dish_id: count}
    cartTotal: { count: 0, price: '0.00' },
    currentMerchantId: null // 当前商家ID
  },

  onLoad() {
    this.initPage();
  },

  onShow() {
    this.initPage();
  },

  // 初始化页面
  initPage() {
    const app = getApp();
    
    // 检查是否选择了商家
    if (!app.globalData.selectedMerchant) {
      wx.showModal({
        title: '提示',
        content: '请先选择商家',
        showCancel: false,
        success: () => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      });
      return;
    }

    const merchantId = app.globalData.selectedMerchant.merchant_id;

    // 检查是否切换了商家
    if (this.data.currentMerchantId !== merchantId) {
      // 商家切换了，重置所有数据
      this.setData({
        categories: [],
        dishes: [],
        dishGroups: [],
        activeCategory: 0,
        keyword: '',
        currentMerchantId: merchantId
      });
    }

    // 从全局获取购物车数据
    const cart = app.globalData.cart || [];
    this.updateCartData(cart);
    
    // 加载分类和菜品
    this.loadCategories();
  },

  // 加载分类
  loadCategories() {
    const app = getApp();
    if (!app.globalData.selectedMerchant) return;
    
    const merchantId = app.globalData.selectedMerchant.merchant_id;
    this.setData({ loading: true });
    
    request.get('/api/category/list', { merchantId }).then(res => {
      if (res.success && res.data.length > 0) {
        this.setData({ 
          categories: res.data,
          activeCategory: res.data[0].category_id
        });
        
        // 加载菜品
        this.loadDishes();
      } else {
        // 处理无分类数据的情况
        this.setData({ categories: [], loading: false });
        wx.showToast({ title: '暂无分类数据', icon: 'none' });
      }
      
      this.setData({ loading: false });
    }).catch(error => {
      console.error('分类加载失败:', error);
      this.setData({ loading: false });
      wx.showToast({ title: '分类加载失败', icon: 'none' });
    });
  },

  // 加载菜品
  loadDishes() {
    const app = getApp();
    if (!app.globalData.selectedMerchant) return;
    
    const merchantId = app.globalData.selectedMerchant.merchant_id;
    const params = { merchantId };
    
    // 如果有搜索关键词
    if (this.data.keyword) {
      params.keyword = this.data.keyword;
      
      request.get('/api/dish/search', params).then(res => {
        if (res.success) {
          this.setData({ dishes: res.data });
          this.groupDishesByCategory();
        } else {
          this.setData({ dishes: [] });
          wx.showToast({ title: '未找到匹配菜品', icon: 'none' });
        }
      }).catch(error => {
        console.error('搜索菜品失败:', error);
        this.setData({ dishes: [] });
        wx.showToast({ title: '搜索失败', icon: 'none' });
      });
    } else {
      // 常规加载
      request.get('/api/dish/list', params).then(res => {
        if (res.success) {
          this.setData({ dishes: res.data });
          this.groupDishesByCategory();
        } else {
          this.setData({ dishes: [] });
          wx.showToast({ title: '暂无菜品数据', icon: 'none' });
        }
      }).catch(error => {
        console.error('菜品加载失败:', error);
        this.setData({ dishes: [] });
        wx.showToast({ title: '菜品加载失败', icon: 'none' });
      });
    }
  },

  // 按分类分组菜品
  groupDishesByCategory() {
    const { dishes, categories, activeCategory, keyword } = this.data;
    let dishGroups = [];
    
    // 创建分类映射
    const categoryMap = {};
    categories.forEach(cat => {
      categoryMap[cat.category_id] = cat.name;
    });
    
    // 筛选菜品
    let filteredDishes = dishes;
    
    // 如果有选中的分类且不是搜索模式，则筛选对应分类的菜品
    if (activeCategory && !keyword) {
      filteredDishes = dishes.filter(dish => dish.category_id === activeCategory);
    }
    
    // 按分类分组
    const groupMap = {};
    filteredDishes.forEach(dish => {
      const categoryId = dish.category_id;
      if (!groupMap[categoryId]) {
        groupMap[categoryId] = {
          categoryId,
          categoryName: categoryMap[categoryId] || '未分类',
          dishes: []
        };
      }
      groupMap[categoryId].dishes.push(dish);
    });
    
    // 转换为数组
    dishGroups = Object.values(groupMap);
    this.setData({ dishGroups });
  },

  // 切换分类
  switchCategory(e) {
    const categoryId = parseInt(e.currentTarget.dataset.id);
    
    this.setData({ 
      activeCategory: categoryId,
      keyword: '' // 切换分类时清空搜索
    });
    
    // 重新分组显示菜品
    this.groupDishesByCategory();
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value.trim();
    this.setData({ keyword });
    
    // 输入节流
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    
    this.searchTimer = setTimeout(() => {
      if (keyword) {
        // 搜索模式：显示所有匹配的菜品
        const filteredDishes = this.data.dishes.filter(dish => 
          dish.name.toLowerCase().includes(keyword.toLowerCase())
        );
        
        const { categories } = this.data;
        const categoryMap = {};
        categories.forEach(cat => {
          categoryMap[cat.category_id] = cat.name;
        });
        
        const groupMap = {};
        filteredDishes.forEach(dish => {
          const categoryId = dish.category_id;
          if (!groupMap[categoryId]) {
            groupMap[categoryId] = {
              categoryId,
              categoryName: categoryMap[categoryId] || '未分类',
              dishes: []
            };
          }
          groupMap[categoryId].dishes.push(dish);
        });
        
        const dishGroups = Object.values(groupMap);
        this.setData({ dishGroups });
      } else {
        // 清空搜索时恢复分类筛选
        this.groupDishesByCategory();
      }
    }, 500);
  },

  // 显示菜品详情
  showDishDetail(e) {
    const dish = e.currentTarget.dataset.dish;
    wx.showModal({
      title: dish.name,
      content: dish.description || '暂无详细描述',
      showCancel: false
    });
  },

  // 添加到购物车
  addToCart(e) {
    const app = getApp();
    const dish = e.currentTarget.dataset.dish;
    let cart = app.globalData.cart || [];
    
    // 检查是否已在购物车中
    const index = cart.findIndex(item => item.dish_id === dish.dish_id);
    
    if (index > -1) {
      // 已在购物车中，数量+1
      cart[index].quantity += 1;
    } else {
      // 不在购物车中，添加
      cart.push({
        dish_id: dish.dish_id,
        name: dish.name,
        price: dish.price,
        image: dish.image,
        quantity: 1,
        merchant_id: this.data.currentMerchantId // 添加商家ID
      });
    }
    
    // 更新全局购物车
    app.globalData.cart = cart;
    
    // 更新本页购物车数据
    this.updateCartData(cart);
    
    // 提示
    wx.showToast({
      title: '已添加到购物车',
      icon: 'success',
      duration: 1000
    });
  },

  // 从购物车减少
  minusFromCart(e) {
    const app = getApp();
    const dish = e.currentTarget.dataset.dish;
    let cart = app.globalData.cart || [];
    
    // 查找购物车中的菜品
    const index = cart.findIndex(item => item.dish_id === dish.dish_id);
    
    if (index > -1) {
      if (cart[index].quantity > 1) {
        // 数量大于1，减1
        cart[index].quantity -= 1;
      } else {
        // 数量为1，从购物车移除
        cart.splice(index, 1);
      }
      
      // 更新全局购物车
      app.globalData.cart = cart;
      
      // 更新本页购物车数据
      this.updateCartData(cart);
    }
  },

  // 更新购物车数据
  updateCartData(cart) {
    // 只统计当前商家的菜品
    const currentMerchantCart = cart.filter(item => 
      item.merchant_id === this.data.currentMerchantId
    );
    
    // 计算购物车映射和总计
    const cartMap = {};
    let totalCount = 0;
    let totalPrice = 0;
    
    currentMerchantCart.forEach(item => {
      cartMap[item.dish_id] = item.quantity;
      totalCount += item.quantity;
      totalPrice += item.price * item.quantity;
    });
    
    this.setData({
      cartMap,
      cartTotal: {
        count: totalCount,
        price: util.formatPrice(totalPrice)
      }
    });
  },

  // 去购物车
  goToCart() {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  },
});    